package thread.threadpool;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池中异常跟踪
 * 异常被线程池吃掉：解决方案：1.改用execute方法提交任务
 * 2. 拓展线程池，对submit方法进行包装
 *
 * @author liweimin
 * @date 2021/5/24 15:48
 * @since
 */
public class Test06 {
    private static class DivideTask implements Runnable {
        private int x;
        private int y;

        public DivideTask(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "计算：" + x + " / " + y + " = " + (x / y));
        }
    }

    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println(t.getName() + "发生了异常：" + e.getMessage()));
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new SynchronousQueue<>());

        for (int i = 0; i < 5; i++) {
            //10/0 异常被吃掉
//            threadPoolExecutor.submit(new DivideTask(10, i));
            threadPoolExecutor.execute(new DivideTask(10, i));
        }
    }
}
